package download

import (
	"errors"
	"fmt"
	"io"
	"net/http"
	"os"
	"path"
)

type Downloader struct {
	concurrency int
	url         string
}

func NewDownloader(n int, targetUrl string) *Downloader {
	return &Downloader{
		concurrency: n,
		url:         targetUrl,
	}
}

func (d *Downloader) Download(fileName string) error {
	if fileName == "" {
		fileName = path.Base(d.url)
	}
	fmt.Println("file name : ", fileName)
	resp, err := http.Get(d.url)
	if err != nil {
		return err
	}
	fmt.Println("response : ", resp.Header.Get("Accept-Ranges"))
	
	/*if resp.StatusCode == http.StatusOK && resp.Header.Get("Accept-Ranges") == "bytes" {
		// 支持部分请求
		return d.multiDownload()
	}*/

	return d.singleDownload(resp, fileName)
}

// 单线程下载
func (d *Downloader) singleDownload(response *http.Response, fileName string) error {
	fmt.Println("single")
	if response.StatusCode != http.StatusOK {
		return errors.New("connection failed.")
	}
	defer response.Body.Close()

	fmt.Println("response.StatusCode : ", response.StatusCode)
	file, err := os.Create(fileName)
	if err != nil {
		return err
	}
	defer file.Close()
	fmt.Println("error : ", err)
	_, err = io.Copy(file, response.Body)
	if err != nil {
		return err
	}
	return nil
}

// 多线程下载
func (d *Downloader) multiDownload() error {
	return nil
}

func (d *Downloader) DownloadPartialFile() {

}

func (d *Downloader) MergeFile() {

}
